<template>
  <div class="myVideo">
    <div v-html="remoteStream" :class="remoteStream?'distant-stream':''"></div>
    <div id="local_stream" class="local-stream"></div>
  </div>
</template>

<script>
import LibGenerateTestUserSig from "../config/lib-generate-test-usersig.min";
import TRTC from "trtc-js-sdk";
export default {
  name: "myVideo",
  components: {},
  data() {
    return {
      fullWidth: document.documentElement.clientWidth,
      fullHeight: document.documentElement.clientHeight,
      userId: "user_1420", //用户id --可更改
      roomId: 888888, //房间号--加入相同房间才能聊
      client: "", //客户端服务
      remoteStream: "", //远方播放流
      localStream: "" //本地流
    };
  },
  methods: {
    /**
     * 动态获取浏览器宽高
     */
    handleResize() {
      this.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = document.documentElement.clientHeight;
    },

    //创建链接
    createClient(userId) {
      //获取签名
      const config = this.genTestUserSig(userId);
      const sdkAppId = config.sdkAppId;
      const userSig = config.userSig;
      this.client = TRTC.createClient({
        mode: "videoCall",
        sdkAppId,
        userId,
        userSig
      });
      //注册远程监听，要放在加入房间前--这里用了发布订阅模式
      this.subscribeStream(this.client);
      //初始化后才能加入房间
      this.joinRoom(this.client, this.roomId);
    },
    //加入房间
    joinRoom(client, roomId) {
      client
        .join({ roomId })
        .catch(error => {
          console.error("进房失败 " + error);
        })
        .then(() => {
          console.log("进房成功");
          //创建本地流
          this.createStream(this.userId);
          //播放远端流
          this.playStream(this.client);
        });
    },

    //创建本地音视频流
    createStream(userId) {
      const localStream = TRTC.createStream({
        userId,
        audio: true,
        video: true
      });
      this.localStream = localStream;

      localStream
        .initialize()
        .catch(error => {
          console.error("初始化本地流失败 " + error);
        })
        .then(() => {
          console.log("初始化本地流成功");
          // 创建好后才能播放 本地流播放 local_stream 是div的id
          localStream.play("local_stream");
          //创建好后才能发布
          this.publishStream(localStream, this.client);
        });
    },

    //发布本地音视频流
    publishStream(localStream, client) {
      client
        .publish(localStream)
        .catch(error => {
          console.error("本地流发布失败 " + error);
        })
        .then(() => {
          console.log("本地流发布成功");
        });
    },

    //订阅远端流--加入房间之前
    subscribeStream(client) {
      client.on("stream-added", event => {
        const remoteStream = event.stream;
        console.log("远端流增加: " + remoteStream.getId());
        //订阅远端流
        client.subscribe(remoteStream);
      });
    },

    //播放远端流
    playStream(client) {
      client.on("stream-subscribed", event => {
        const remoteStream = event.stream;
        console.log("远端流订阅成功：" + remoteStream.getId());
        // 创建远端流标签，因为id是动态的，所以动态创建，用了v-html

        this.remoteStream = `<view id="${"remote_stream-" +
          remoteStream.getId()}"  ></view>`;

        //做了dom操作 需要使用$nextTick(),否则找不到创建的标签无法进行播放
        this.$nextTick(() => {
          //播放
          remoteStream.play("remote_stream-" + remoteStream.getId());
        });
      });
    },

    //退出音视频
    leaveRoom(client) {
      client
        .leave()
        .then(() => {
          console.log("退房成功");
          // 停止本地流，关闭本地流内部的音视频播放器
          this.localStream.stop();
          // 关闭本地流，释放摄像头和麦克风访问权限
          this.localStream.close();
          this.localStream = null;
          this.client = null;
          // 退房成功，可再次调用client.join重新进房开启新的通话。
        })
        .catch(error => {
          console.error("退房失败 " + error);
          // 错误不可恢复，需要刷新页面。
        });
    },

    //获取用户签名--前端测试用
    genTestUserSig(userID) {
      const SDKAPPID = 1400364762;

      const EXPIRETIME = 604800;

      const SECRETKEY =
        "7f29b1d2911c548345a860272a24a19a306ca34a3edf4846dd057796c1199d12";

      // a soft reminder to guide developer to configure sdkAppId/secretKey
      if (SDKAPPID === "" || SECRETKEY === "") {
        alert(
          "请先配置好您的账号信息： SDKAPPID 及 SECRETKEY " +
            "\r\n\r\nPlease configure your SDKAPPID/SECRETKEY in js/debug/GenerateTestUserSig.js"
        );
      }
      const generator = new LibGenerateTestUserSig(
        SDKAPPID,
        SECRETKEY,
        EXPIRETIME
      );
      const userSig = generator.genTestUserSig(userID);
      return {
        sdkAppId: SDKAPPID,
        userSig: userSig
      };
    }
  },
  mounted() {
    //const that = this;
    //测试用，所以直接创建了，其他需求可自行更改
    //this.createClient(this.userId);
  },
  created() {
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy: function() {
    window.removeEventListener("resize", this.handleResize);
  }
};
</script>

<style lang="scss" scoped>
.myVideo {
  //本地流
  .local-stream {
    width: 500px;
    height: 500px;
  }
  //远端流
  .distant-stream {
    width: 200px;
    height: 200px;
  }
}
</style>